package top.system.dept.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import top.system.dept.pojo.Invoice;
import top.system.dept.pojo.InvoiceItem;
import top.system.dept.pojo.SysResp;
import top.system.dept.service.InvoiceService;
import top.system.dept.utils.IOUtil;
import top.system.dept.utils.RespUtil;

import javax.servlet.ServletInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/invoice")
public class InvoiceController {

    @Autowired
    InvoiceService invoiceService;

    @RequestMapping("/upload")
    public SysResp uploadInvoice(MultipartFile[] files, String userModal, MultipartHttpServletRequest req, Invoice invoice) {

        String invoiceItems = req.getParameter("invoiceItems");
        ObjectMapper om = new ObjectMapper();

        try {
            InvoiceItem[] itemList = om.readValue(invoiceItems, new TypeReference<InvoiceItem[]>() {});
            invoice.setItems(Arrays.asList(itemList));
            return invoiceService.uploadInvoice(files, userModal, invoice, itemList, req);
        } catch (JsonProcessingException e) {
            return RespUtil.illegalParam();
        }

    }

    @RequestMapping("/get")
    public SysResp getInvoice(String userModal) {
        return invoiceService.getInvoicesByModal(userModal);
    }

    @RequestMapping("/get/byDate")
    @ResponseBody
    public SysResp getInvoice(@RequestBody Map<String, String> data) {
        String userModal = data.get("userModal");
        String beginDate = data.get("beginDate"); // timestamp
        String endDate = data.get("endDate"); // timestamp

        try {
            long begin = Long.parseLong(beginDate);
            long end = Long.parseLong(endDate);
            return invoiceService.getInvoiceByDate(userModal, begin, end);
        } catch (NumberFormatException ex) {
            return RespUtil.illegalParam();
        }

    }

}
